package proxy.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author mubei
 * @date 2021/12/14
 * @description
 */
public class ProxyFactory implements MethodInterceptor {
    // 目标对象
    Object target;

    public ProxyFactory(Object target) {
        this.target = target;
    }

    // 返回目标对象的代理对象
    public Object getProxyInstance(){
        //1. 创建一个工具类
        Enhancer enhancer = new Enhancer();
        //2.设置父类
        enhancer.setSuperclass(target.getClass());
        //3.设置回调函数   MethodInterceptor 就是 Callback  使用intercept
        enhancer.setCallback(this);
        //4创建子类  代理对象
        return enhancer.create();
    }

    // 该方法会调用目标对象的方法
    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        System.out.println("Cglib代理模式开始~~~~");
        Object returnValue = method.invoke(target, args);
        System.out.println("Cglib代理模式结束咯~~~");
        return returnValue;
    }
}
